package com.ngkj.zmfptback.sys.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ChenHN
 * @since 2021/12/7 creation
 **/

@Service
public class EmailService {

    public final static String r = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Autowired
    JavaMailSenderImpl sender;

    @Autowired
    HttpServletRequest request;

    @Value("${spring.mail.username}")
    private String fromMail;


    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 发送邮箱验证码
     * redis 保存验证码 设置过期时间
     * @param email
     */
    public void sendVercode(String email){
        String s="";
        int len=r.length();
        Random random = new Random();
        for (int i = 0; i <4 ; i++) {
            int index = random.nextInt(len);
            s += r.charAt(index);
        }
        SimpleMailMessage message = new SimpleMailMessage();
        String cacheName = "email_"+email;
        message.setSubject("欢迎注册弄个房租平台，请接收验证码：");
        message.setText("邮箱验证码为："+s+"\n\n\n验证码将于5分钟后过期，请及时验证!");
        message.setTo(email);
        message.setFrom(fromMail);
        redisTemplate.opsForValue().set(cacheName,s,300, TimeUnit.SECONDS);
        sender.send(message);
    }

    /**
     * 验证邮箱是否正确
     * @param email 邮箱
     * @return
     */
    public boolean isEmail(String email){
        if (email==null || "".equals(email)){
            return false;
        }
        Pattern emailPattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        Matcher matcher = emailPattern.matcher(email);
        if (matcher.find()) {
            return true;
        }else {
            return false;
        }
    }


}

